package ext.tianma.part.util.updateIBAValues;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import com.ptc.core.meta.common.impl.LogicalAttributeFormatException;
import java.util.Hashtable;
import ext.com.core.CoreUtil;
import ext.tianma.bom.service.FinishedGoodService;
import ext.tianma.bom.util.ClassificationUtil;
import ext.tianma.bom.util.GenericUtil;
import ext.tianma.bom.util.LWCUtil;
import ext.tianma.bom.util.StringUtil;
import ext.tianma.part.Interface.Until.ClassificationMDM;
import wt.csm.navigation.ClassificationNode;
import wt.fc.ObjectReference;
import wt.fc.QueryResult;
import wt.fc.WTObject;
import wt.fc.collections.WTArrayList;
import wt.log4j.LogR;
import wt.method.RemoteAccess;
import wt.part.WTPart;
import wt.part.WTPartMaster;
import wt.session.SessionServerHelper;
import wt.util.WTException;
import wt.vc.Iterated;
import wt.vc.config.ConfigHelper;
import wt.vc.config.ConfigSpec;
import wt.vc.config.LatestConfigSpec;

/**
 * 分类属性信息同步编辑Design同步到所有的生效视图
 * 
 * @author laichao_sun
 *
 */

public class ClassificationSynchronization implements RemoteAccess {
	private static final Logger log = LogR.getLogger(ClassificationSynchronization.class.getName());
	private static final String D_VIEW = "Design";

	public static void getClassification(WTObject object) {
		try {
			WTArrayList partList = new WTArrayList();
			WTPart part2 = null;
			if (object instanceof WTPart) {
				part2 = (WTPart) object;
			}
			WTPart part = CoreUtil.getWTPartByMasterAndView((WTPartMaster) part2.getMaster(), D_VIEW);

			// 获取部件分类节点的全路径名称
			String string = ClassificationUtil.getClassification(part);
			if (StringUtil.isNullOrEmpty(string)) {
				log.info("SLC ======Design视图部件没有分类属性==>");
				return;
			}
			// Design视图的部件的分类属性
			List<HashMap<String, String>> list2 = ClassificationMDM
					.getClassifictionIba(ClassificationUtil.getClassificationNode(part).getName(), part);
			Map<String, String> maps = new HashMap<String, String>();
			for (HashMap<String, String> map : list2) {
				String displayname = map.get("displayname");
				String value = map.get("value");
				String key = map.get("key");
				maps.put(key, value == null ? "" : value);
			}
			if (maps.isEmpty()) {
				log.info("SLC ======Design视图部件没有分类属性==>");
				return;
			}
			// 各个非Design视图的部件的分类属性
			Map<String, String> map = getMaterialsClassification(part2.getNumber());
			if (map.isEmpty()) {
				log.info("SLC ======非Design视图部件没有分类属性,无法同步属性==>" + part2.getNumber() + " | 视图: "
						+ part.getView().getName());
				return;
			}

			System.out.println("同步分类属性 Design视图:" + maps.toString() + " | " + part2.getView().getName() + ":" + map.toString());
			Iterator<String> keys = maps.keySet().iterator();
			boolean flag = SessionServerHelper.manager.setAccessEnforced(false);

			while (keys.hasNext()) {
				String key = (String) keys.next();
				String value = maps.get(key); // 为部件设置分类属性

				if (map.containsKey(key)) {
					LWCUtil.setValue(part2, key, value);
				}

			}
			SessionServerHelper.manager.setAccessEnforced(flag);

			log.info("SLC ===分类同步完成==>");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 获取分类属性值
	 * 
	 * @param number
	 * @return
	 */
	public static Map<String, String> getMaterialsClassification(String number) {
		JSONObject result = new JSONObject();
		Map<String, String> maps = new HashMap<String, String>();
		try {
			WTPart part = GenericUtil.getPart(number, "");
			if (part == null) {
				result.put("datalist", "");
			}
			// String classtype = (String) LWCUtil.getValue(part, "SemiFinishedGoodType");
			// //System.out.println("=====getMaterialsClassification classtype:" +
			// classtype);

			List<HashMap<String, String>> list = getNodeIBAByPart2(part);
			JSONObject object = new JSONObject();
			for (HashMap<String, String> map : list) {
				String displayname = map.get("displayname");
				String value = map.get("value");
				String key = map.get("key");
				object.put(displayname, value == null ? "" : value);
				maps.put(key, value);
			}
			result.put("datalist", object);
		} catch (Exception e) {
			log.info("===getMaterialsClassification Exception:" + e);
		}
		return maps;
	}

	/**
	 * 根据part获取分类 返回分类属性的值（显示名称、key、value）
	 */
	public static List<HashMap<String, String>> getNodeIBAByPart2(WTPart part) {
		List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();

		ClassificationNode node = ClassificationUtil.getClassificationNode(part);
		try {
			Hashtable values = ext.com.iba.IBAUtil.getIBAValues(node);
			Iterator ibaiter = values.keySet().iterator();
			while (ibaiter.hasNext()) {
				String key = ibaiter.next().toString();
				if (values.get(key) != null && values.get(key) instanceof String) {
					HashMap<String, String> ibamap = new HashMap<String, String>();
					String displayname = FinishedGoodService.queryDisplayName(key, "string");
					if ("".equals(displayname)) {
						displayname = FinishedGoodService.queryDisplayName(key, "float");
						if ("".equals(displayname)) {
							displayname = FinishedGoodService.queryDisplayName(key, "timestamp");
						}
					}
					String value = (String) values.get(key);
					try {
						// value = (String) LWCUtil.getValue(part, key);
						Object obj = LWCUtil.getValue(part, key);
						if (obj instanceof String) {
							value = (String) obj;
						} else if (obj instanceof Float) {
							value = Float.toString((Float) obj);
							displayname = FinishedGoodService.queryDisplayName(key, "float");
						} else if (obj instanceof Integer) {
							value = Integer.toString((Integer) obj);
						}
						if (StringUtil.isNullOrEmpty(value)) {
							String value2 = "";
							Object obj2 = LWCUtil.getValue(part, "cn.tianma." + key);
							if (obj2 instanceof String) {
								value2 = (String) obj2;
							} else if (obj2 instanceof Float) {
								value2 = Float.toString((Float) obj2);
								displayname = FinishedGoodService.queryDisplayName(key, "float");
							} else if (obj2 instanceof Integer) {
								value2 = Integer.toString((Integer) obj2);
							}

							if (!StringUtil.isNullOrEmpty(value2)) {
								value = value2;
							}
						}
					} catch (LogicalAttributeFormatException e) {
						e.printStackTrace();
					}

					ibamap.put("displayname", displayname);
					ibamap.put("key", key);
					ibamap.put("value", value == null ? "" : value);
					list.add(ibamap);
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;

	}

	// 获取最新的部件
	@SuppressWarnings("deprecation")
	public static WTPart getLatestPartByPartMaster(WTPartMaster paramWTPartMaster) throws WTException {
		Iterated localIterated = null;
		boolean bool = false;
		LatestConfigSpec localLatestConfigSpec = new LatestConfigSpec();

		QueryResult localQueryResult = ConfigHelper.service.filteredIterationsOf(paramWTPartMaster,
				localLatestConfigSpec);
		if ((localQueryResult != null) && (localQueryResult.size() <= 0)) {
			ConfigSpec localConfigSpec = ConfigHelper.service.getDefaultConfigSpecFor(WTPartMaster.class);
			localQueryResult = ConfigHelper.service.filteredIterationsOf(paramWTPartMaster, localConfigSpec);
		}

		while ((localQueryResult.hasMoreElements()) && (!bool)) {
			localIterated = (Iterated) localQueryResult.nextElement();
			bool = localIterated.isLatestIteration();
		}
		return (WTPart) localIterated;
	}

}
